package com.niiwoo.civet.trade.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.constant.RabbitConstant;
import com.niiwoo.civet.trade.dto.response.kaola.KaoLaBaseResponseDTO;
import com.niiwoo.civet.trade.service.koala.KaoLaLiCaiContractDubboService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 考拉理财债权转让(借款人还款逾期时)合同签署listener
 *
 * @author liming
 * @date 2017-12-29 14:28
 */
@Slf4j
@Component
public class KaoLaLiCaiCreditAssignmentContractListener {

    @Reference(version = "1.0.0")
    private KaoLaLiCaiContractDubboService kaoLaLiCaiContractDubboService;

    /**
     * 考拉理财债权转让合同签署
     */
    @RabbitListener(queues = {RabbitConstant.Queue.KAOLA_CREDIT_ASSIGNMENT})
    public void signContract(Long signNotifyRecordId,Message message, Channel channel){
        log.info("考拉债权转让合同签署,消息内容={}",message);
        String signNotifyRecordIdStr = null;
        try {
            signNotifyRecordIdStr = new String(message.getBody(), Charset.forName("UTF-8"));

            if(StringUtils.isEmpty(signNotifyRecordIdStr)){
                log.error("考拉债权转让合同签署,发生异常,原因是由于收到的signNotifyRecordId为空.");
            }
            log.info("考拉债权转让合同签署,signNotifyRecordId={}",signNotifyRecordIdStr);
            KaoLaBaseResponseDTO responseDTO =  kaoLaLiCaiContractDubboService.autoSignForKaolaDebt(Long.valueOf(signNotifyRecordIdStr));
            if(!responseDTO.isSuccess()){
                log.error("考拉债权转让合同签署,signNotifyRecordId={},发生异常,原因签署失败,结果如下:{}",signNotifyRecordId,responseDTO);
            }
        } catch (Exception e) {
            log.error("考拉债权转让合同签署,signNotifyRecordId={},发生系统异常,原因如下:{}",e);
        }finally{
            doAckAnwser(message, channel);
        }
    }

    private void doAckAnwser(Message message, Channel channel)
    {
        try {
            //确认消息已经接收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException ie) {
            log.error("basic ack occur exception, the reason is : {}", ie);
        }
    }
}
